package de.haw.shc.Config;

import android.content.res.Resources;
import android.util.Log;
import de.haw.shc.Interfaces.DeviceProperty.Device;
import de.haw.shc.R;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import java.io.*;
import java.util.List;
import java.util.Map;



/**
 * Created with IntelliJ IDEA.
 * User: mizus
 * Date: 29.05.13
 * Time: 13:50
 * To change this template use File | Settings | File Templates.
 */
public class XML_Reader {



    private static XML_Reader instance;
    private final int DEVICE = 0;
    private final int ROOM = 1;

    private Map<String, List<Device>> roomMap, deviceMap;


    private InputStream  inputStream;


    private XML_Reader(Resources aIS){
        inputStream = aIS.openRawResource(R.raw.config);
        roomMap = read(ROOM);
        inputStream = aIS.openRawResource(R.raw.config);
        deviceMap = read(DEVICE);
    }



    public static XML_Reader getInstance(){
        return instance;
    }

    public static XML_Reader createXMLReader(Resources inputStream){
        if (instance == null) instance = new XML_Reader(inputStream);
        return instance;
    }


    public Map<String, List<Device>> getDeviceMap(){
        return deviceMap;
    }

    public Map<String, List<Device>> getRaumMap(){
        return roomMap;
    }


    private Map<String,List<Device>> read(int device)  {
        Map<String, List<Device>> result = null;
        Device_Content_Handler dch = new Device_Content_Handler();
        try {
            SAXParserFactory  factory = SAXParserFactory.newInstance();

            factory.setValidating(false);


            // Gdx.files.local();

            factory.newSAXParser().parse(inputStream, dch);

            switch (device){
                case ROOM:
                    result = dch.getMap_by_Room();
                    break;
                case DEVICE:
                    result = dch.getMap_by_Device();
                    break;
            }


        } catch (SAXException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        Log.d("XML-Parser", "Map: " + result);


        return result;
    }




}
